import { defineComponent, onMounted, ref, watch, onBeforeUnmount } from 'vue'
import { useRouter, useCurrentInstance } from '@src/modules/intelligentQuality/hooks/index.ts'

/* components */
import ExecuteEcharts from '@src/modules/intelligentQuality/views/details/executeEcharts.tsx'
import EditQualityDialog from '@src/modules/intelligentQuality/views/editQualityDialog/index.tsx'
import BaseFileItem from '@src/component/common/BaseFileItem/BaseFileItem.vue'
import QualityTableData from '@src/modules/intelligentQuality/views/details/components/tableData/index.tsx'
import BaseCollapse  from '@src/component/common/BaseCollapse/BaseCollapse.vue'
/* http */
import { getRobotDetail, getQualityRun, switchRobot, deleteRobot } from '@src/api/intelligentQuality.js'
/* scss */
import "@src/modules/intelligentQuality/views/details/index.scss"
/* utils */
import { t } from '@src/locales';
import { openAccurateTab } from '@src/util/platform'
import platform from '@src/platform/index.js'
import { getGray } from '@src/modules/intelligentQuality/utils/index.ts'
import state from '@src/modules/intelligentQuality/utils/state.ts'
/* type */
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { message, confirm } from '@src/util/message'
import { isFalse, isFalsy } from '@src/util/type'
import dayjs from 'dayjs';
/* type */
import { executeTotal as executeTotalT } from '@src/modules/intelligentQuality/type/index.ts'
/* hooks */
import { useGetDataInfo } from '@src/modules/intelligentQuality/hooks/useGetDataInfo.ts'


export default defineComponent({
    name: 'intelligentRobotDetail',
    props: {

    },
    setup() {
        const { query } = useRouter()
        const { robotNo } = query
        const loading = ref(false)
        const loadingRight = ref(true)
        const loadingTable = ref(true) // 表格loading
        const robotIntelligentDetail = ref({})
        const executeInfo = ref({})
        const executeTotal = ref<executeTotalT>('valid')
        const qualityDialog = ref<HTMLDivElement | null>(null)
        const { getQualityDataInfoFetch }  = useGetDataInfo()
        const collapseDirection = ref('')
        const rightBoxRef = ref<HTMLElement | null>(null)
        const echartsRef = ref<InstanceType<typeof ExecuteEcharts> | null>(null)


        const [currentCtx] = useCurrentInstance()
        const executeTotalEnum = {
            'totalCheckNum': '总质检量',
            'validCheckNum': '有效质检量',
            'paasCheckNum': '质检合格量',
            'paasCheckRate': '质检合格率',
            'exceptionCheckNum': '质检异常量',
            'exceptionCheckRate': '质检异常率'
        }
        // 选择时间值
        const currentDate = ref('last7')
        // 时间范围
        const timeRange = ref([
            {
                label: '最近7日',
                value: 'last7',
                active: true
            },
            {
                label: '最近30日',
                value: 'last30',
                active: false
            },
            {
                label: '本月',
                value: 'currM',
                active: false
            },
            {
                label: '今年',
                value: 'currY',
                active: false
            },
            {
                label: '全部',
                value: 'all',
                active: false
            }
        ])
        // 表格数据配置信息
        const tableOptions = ref({
            total: 0,
            pageNum: 1,
            pageSize: 10
        })
        // 表格数据信息
        const tableData = ref([])

        const initAuthRobot = () => {
            const authRes = getGray()
            state.auth.create =   Reflect.has(authRes.user?.auth, 'INTELLIGENT_ROBOT_CREATE')
            state.auth.edit = Reflect.has(authRes.user?.auth, 'INTELLIGENT_ROBOT_EDIT')
            state.auth.delete = Reflect.has(authRes.user?.auth, 'INTELLIGENT_ROBOT_DELETE')
          }
          initAuthRobot()

        /**
         * @description 获取质检机器人执行数据情况
         */
        const getTableInfoFetch = async () => {
            try {
                loadingTable.value = true;
                const res = await getQualityDataInfoFetch({
                    robotNo,
                    periodType: currentDate.value,
                    countType: executeTotal.value,
                    pageNum: tableOptions.value.pageNum,
                    pageSize: tableOptions.value.pageSize,
                })
                if (!res.success) {
                    message.error(res.message)
                    return
                }
                loadingTable.value = false
                tableData.value = res.data.list
                tableOptions.value.total = res.data.total
            } catch (error) {
                console.error(error)
                loadingTable.value = false
            }
        }

        /**
         * @description 获取机器人详情
         */
        const getDetailInfo = async () => {
            try {
                loading.value = true
                const res = await getRobotDetail({ robotNo })
                if (!res.success) {
                    message.error(res.message || t('robot.text20'))
                    return
                }
                robotIntelligentDetail.value = res.data
                loading.value = false
            } catch (error) {
                console.error(error)
            }
        }

        /**
         * @description 获取执行信息
         */
        const getExecuteInfo = async () => {
            try {
                const res = await getQualityRun({ robotNo })
                if (!res.success) {
                    message.error(res.message || t('robot.text20'))
                    return
                }
                executeInfo.value = res.data
                loadingRight.value = false
            } catch (error) {
                console.error(error)
            }
        }

        /**
         * @description 选中不同tab
         * @param tab 
         */
        const changeTab = (tab: executeTotalT) => {
            executeTotal.value = tab
        }

        /**
         * @description 切换开关
         */
        const handlerChange = async (val: boolean) => {
            try {
                const res = await switchRobot({
                    robotNo: robotNo,
                    enabled: val
                })
                if (!res.success) {
                    message.error(res.message || t('robot.text21'))
                    return
                }
                // @ts-ignore
                robotIntelligentDetail.value.enabled = val
                if (val) {
                    message.success(t('robot.text22'))
                } else {
                    message.success(t('robot.text23'))
                }
                refreshFromTab()
            } catch (error) {
                console.error(error)
            }
        }

        const editNameHandler = () => {
            if (!qualityDialog.value) return
            qualityDialog.value.modelForm = {
                robotName: robotIntelligentDetail.value?.name || '',
                robotDesc: robotIntelligentDetail.value?.remarks || ''
            }
            qualityDialog.value.formId = robotNo
            qualityDialog.value?.showDialog()
        }

        const refreshCurrentId = () => {
            const fromId = window?.frameElement?.getAttribute('id') as string
            platform.refreshTab(fromId)
        }
        
        const closeTab = () => {
            // @ts-ignore
            const id = window.frameElement?.dataset?.id
            platform.closeTab(id)
        }
        
        const refreshFromTab = () => {
            let fromId = window?.frameElement?.getAttribute('fromid')
            platform.refreshTab(fromId)
        }

        /**
         * @description 删除操作
         */
        const deleteHandler = async () => {
            try {
                const res = await confirm.warning(t('robot.text24'), t('robot.tip'))
                if (isFalse(res)) {
                    return
                }
                loading.value = true
                const result = await deleteRobot({robotNo})
                if (!result.success) {
                    message.error(result.msg || t('robot.text25'))
                    loading.value = false
                    return
                }
                message.success(t('robot.delete1'))
                refreshCurrentId()
                refreshFromTab()
                closeTab()
                loading.value = false
            } catch (error) {
                console.error(error)
            }

        }

        /**
         * @description 编辑规则
         */
        const editHandler = () => {
            let fromId = window?.frameElement?.getAttribute('id')
            // 临时先这样
            openAccurateTab({
              type: PageRoutesTypeEnum.IntelligentQualityEdit,
              params: `robotNo=${robotNo}&isEdit=true`,
              fromId
            })
        }

        /**
         * @description 切换时间范围
         * @param selectedValue 
         */
        const changeTimeRange = (selectedValue: string) => {
            timeRange.value = timeRange.value.map(item => ({
              ...item,
              active: item.value === selectedValue
            }))
            currentDate.value = selectedValue
          }

        /**
         * @description 处理当前页码
         * @param val 
         */
        const handlerCurrentPage = (val: number) => {
            tableOptions.value.pageNum = val
        }
        const updateCollapseDirection = (val) => {
            collapseDirection.value = val
        }
        
        watch([() => currentDate.value, () => tableOptions.value.pageNum, () => executeTotal.value], (newVal) => {
            if (newVal) {
                getTableInfoFetch()
            }
        })

        getTableInfoFetch()
        getDetailInfo()
        getExecuteInfo()

        // 创建 ResizeObserver 实例
        // const resizeObserver = new ResizeObserver((entries) => {
        //     for (let entry of entries) {
        //       if (entry.target === rightBoxRef.value && echartsRef.value) {
        //         echartsRef.value.draw() // 假设 draw 是重新绘制图表的方法
        //       }
        //     }
        // })
      
        // onMounted(() => {
        //   if (rightBoxRef.value) {
        //     resizeObserver.observe(rightBoxRef.value);
        //   }
        // });
      
        // onBeforeUnmount(() => {
        //   if (rightBoxRef.value) {
        //     resizeObserver.unobserve(rightBoxRef.value);
        //   }
        // });

        return {
            rightBoxRef,
            echartsRef,
            collapseDirection,
            tableData,
            tableOptions,
            currentDate,
            timeRange,
            robotNo,
            executeTotalEnum,
            loading,
            loadingTable,
            loadingRight,
            robotIntelligentDetail,
            executeInfo,
            changeTab,
            executeTotal,
            handlerChange,
            editNameHandler,
            deleteHandler,
            qualityDialog,
            editHandler,
            changeTimeRange,
            handlerCurrentPage,
            updateCollapseDirection
        }
    },
    render() {
        return (
            <div class="intelligent-detail" v-loading={this.loading}>
                <div class="detail-container">
                    <div class="header">
                        <div class="tilte">
                            {this.robotIntelligentDetail.name}
                            </div>
                        <div class="act">
                            <div class="act-group">
                                <el-switch active-value={true} inactive-value={false} value={this.robotIntelligentDetail.enabled} onChange={(val) => this.handlerChange(val)}></el-switch>
                                {
                                    this.robotIntelligentDetail.enabled ? (
                                        <span class="work">{t('robot.worktext')}</span>
                                    ) : (
                                            <span class="disabled">{t('robot.worktext1')}</span>
                                        )
                                }
                                {
                                    state.auth.edit ? (
                                        <el-button class="act-edit" type={'primary'} onClick={() => this.editHandler()}>{t('robot.editrule1')}</el-button>
                                    ) : null
                                }
                                {
                                    state.auth.delete || state.auth.edit ? (
                                        <div class="act-more">
                                            <el-dropdown>
                                                <el-button type="plain-third">
                                                {t('robot.more')}<i class="el-icon-arrow-down el-icon--right"></i>
                                                </el-button>
                                                <el-dropdown-menu slot="dropdown">
                                                    {
                                                        state.auth.edit ? (
                                                            <el-dropdown-item nativeOnClick={() => this.editNameHandler()}>{t('robot.updateName')}</el-dropdown-item>
                                                        ) : null
                                                    }
                                                    {
                                                        state.auth.delete ? (
                                                            <el-dropdown-item nativeOnClick={() => this.deleteHandler()}>{t('robot.delete4')}</el-dropdown-item>
                                                        ) : null
                                                    }
                                                </el-dropdown-menu>
                                            </el-dropdown>
                                        </div>
                                    ) : null
                                }
                            </div>
                        </div>
                    </div>
                    <div class="content">
                        <BaseCollapse
                            direction={this.collapseDirection}
                            {...{
                                on: {
                                    'update:direction': this.updateCollapseDirection
                                }
                            }}
                        >
                            <div slot="left">
                                <div class="content_left" v-show={this.collapseDirection != 'left'}>
                                <div class="head">基本信息</div>
                                {
                                    this.loading ? null : (
                                        <div class="content_left_item">
                                        <div class="form-view-row">
                                            <label class="form-view-row-label">
                                                {/* {t('robot.text28')} */}
                                                名称
                                            </label>
                                            <div class="form-view-row-content">
                                                {this.robotIntelligentDetail.name || ''}
                                            </div>
                                        </div>
                                        <div class="form-view-row">
                                            <label class="form-view-row-label">
                                                {t('robot.text12')}
                                            </label>
                                            <div class="form-view-row-content">
                                                {this.robotIntelligentDetail.remarks || ''}
                                            </div>
                                        </div>
                                        <div class="form-view-row">
                                            <label class="form-view-row-label">
                                            {t('robot.text29')}
                                            </label>
                                            <div class="form-view-row-content">
                                                {this.robotIntelligentDetail.formName || ''}
                                            </div>
                                        </div>
                                        <div class="form-view-row">
                                            <label class="form-view-row-label">
                                                {
                                                    this.robotIntelligentDetail.fieldList.map(item => {
                                                        return item.cnName
                                                    }).filter(item => !!item).join('/')
                                                }
                                            </label>
                                            <div class="form-view-row-content imgList">
                                                {
                                                    this.robotIntelligentDetail.examplePicList && this.robotIntelligentDetail.examplePicList.length > 0 ? (
                                                        this.robotIntelligentDetail.examplePicList.map((item,index) => {
                                                            return (
                                                                <BaseFileItem 
                                                                    key={index}
                                                                    file={{
                                                                        url: item.ossUrl,
                                                                        id: item.fileId,
                                                                        filename: item.fileName
                                                                    }}
                                                                    readonly={true}
                                                                    source={this.robotIntelligentDetail.examplePicList}
                                                                />
                                                                // <div class="form-view-row-content-imgItem">
                                                                //     <img src={item.ossUrl} class="imgItem"/>
                                                                // </div>
                                                            )
                                                        })
                                                    ) : ''
                                                }
                                            </div>
                                        </div>
                                        <div class="form-view-row">
                                            <label class="form-view-row-label">
                                                {t('robot.text30')}
                                            </label>
                                            <div class="form-view-row-content">
                                                {
                                                    this.robotIntelligentDetail.minPictureCheckScore || 0
                                                }
                                                %&nbsp;及{t('robot.text31')}
                                            </div>
                                        </div>
                                        <div class="form-view-row">
                                            <label class="form-view-row-label">
                                                {t('robot.text32')}
                                            </label>
                                            <div class="form-view-row-content">
                                                {
                                                    `${this.robotIntelligentDetail.minCheckScore || 0}% 及${t('robot.text31')}，${t("robot.text33")}
                                                    ${this.robotIntelligentDetail.minCheckCount || 0} 张及以上`
                                                }
                                            </div>
                                        </div>
                                        <div class="form-view-row">
                                            <label class="form-view-row-label">
                                                {t('robot.text35')}
                                            </label>
                                            <div class="form-view-row-content">
                                                {
                                                    this.robotIntelligentDetail.nowCheck ? t('robot.text36') : t('robot.text37')
                                                }
                                            </div>
                                        </div>
                                        <div class="form-view-row">
                                            <label class="form-view-row-label">
                                                {t('robot.text38')}
                                            </label>
                                            <div class="form-view-row-content">
                                                {
                                                    this.robotIntelligentDetail.createUser?.displayName || ''
                                                }
                                            </div>
                                        </div>
                                        <div class="form-view-row">
                                            <label class="form-view-row-label">
                                            {t('robot.text39')}
                                            </label>
                                            <div class="form-view-row-content">
                                                {
                                                    this.robotIntelligentDetail?.createTime 
                                                    && 
                                                    dayjs(this.robotIntelligentDetail?.createTime).format('YYYY-MM-DD HH:mm:ss') || ''
                                                }
                                            </div>
                                        </div>
                                        </div>
                                    )
                                }
                                </div>
                                <div class="head" v-show={this.collapseDirection == 'left'}>基本信息</div>
                            </div>
                            
                            
                            <div slot="right">
                                <div class="content_right" ref={this.rightBoxRef} slot="right" v-loading={this.loadingRight} v-show={this.collapseDirection != 'right'}>
                                    <div class="head">{t('robot.text40')}</div>
                                    {
                                        this.loadingRight ? null : (
                                            <div class="content_right_item">
                                        <div class="head-action">
                                            <div class="head-action-title">
                                                统计数据
                                            </div>
                                            <div class="head-action-select">
                                                <div class="time-range">时间范围：</div>
                                                <div class="time-range-select">
                                                    {
                                                        this.timeRange.map(item => {
                                                            return (
                                                                <span class={`${item.active ? 'active' : ''}`}  onClick={() => this.changeTimeRange(item.value)}>{ item.label }</span>
                                                            )
                                                        })
                                                    }
                                                </div>
                                            </div>
                                        </div>
                                        <div class="showList">
                                            <div class="item">
                                                <div class="top">{this.executeTotalEnum['totalCheckNum']}</div>
                                                <div class="bottom">{this.executeInfo?.totalCheckNum || '0'}</div>
                                            </div>
                                            <div class="item">
                                                <div class="top">{this.executeTotalEnum['paasCheckRate']}</div>
                                                <div class="bottom">{this.executeInfo?.paasCheckRate || '0'}%</div>
                                            </div>
                                            <div class="item">
                                                <div class="top">{this.executeTotalEnum['exceptionCheckRate']}</div>
                                                <div class="bottom">{this.executeInfo?.exceptionCheckRate || '0'}%</div>
                                            </div>
                                            <div class={`item cursor ${this.executeTotal === 'valid' ? 'active' : ''}`}  onClick={() => this.changeTab('valid')}>
                                                <div class="top">{this.executeTotalEnum['validCheckNum']}</div>
                                                <div class="bottom">{this.executeInfo?.validCheckNum || '0'}</div>
                                            </div>
                                            <div class={`item cursor ${this.executeTotal === 'paas' ? 'active' : ''}`} onClick={() => this.changeTab('paas')}>
                                                <div class="top">{this.executeTotalEnum['paasCheckNum']}</div>
                                                <div class="bottom">{this.executeInfo?.paasCheckNum || '0'}</div>
                                            </div>
                                            <div class={`item cursor ${this.executeTotal === 'exception' ? 'active' : ''}`} onClick={() => this.changeTab('exception')}>
                                                <div class="top">{this.executeTotalEnum['exceptionCheckNum']}</div>
                                                <div class="bottom">{this.executeInfo?.exceptionCheckNum || '0'}</div>
                                            </div>
                                        </div>
                                        <div class="chart">
                                            <ExecuteEcharts ref={el => this.echartsRef = el} robotNo={this.robotNo} executeTotal={this.executeTotal} currentDate={this.currentDate}/>
                                        </div>
                                        <div>
                                            <QualityTableData tableData={this.tableData} tableOptions={this.tableOptions} loadingTable={this.loadingTable} onCurrentPageChange={(val) => this.handlerCurrentPage(val)}/>
                                        </div>
                                            </div>
                                        )
                                    }
                                </div>
                                <div class="head" v-show={this.collapseDirection == 'right'}>{t('robot.text40')}</div>
                            </div>
                        </BaseCollapse>
                        
                    </div>
                </div>
                <EditQualityDialog ref={el => this.qualityDialog = el}/>
            </div>
        )
    }
})